package com.zzyl.nursing.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.dto.ElderDto;
import com.zzyl.nursing.domain.dto.UserLoginRequestDto;
import com.zzyl.nursing.domain.pojo.FamilyMember;
import com.zzyl.nursing.domain.vo.LoginVo;
import com.zzyl.nursing.domain.vo.MyVo;
import com.zzyl.nursing.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 * 
 * @author alexis
 * @date 2025-05-26
 */
@Slf4j
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    TokenService tokenService;


    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return familyMemberMapper.deleteById(id);
    }


    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 一、认证：查找到openId-->family_member表查询出对应的单个用户
        String code = userLoginRequestDto.getCode();
        String openId = wechatService.getOpenId(code);
        FamilyMember member = this.getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId));
        // 二、表维护：获取用户phone和昵称数据-->新增用户或者修改用户
        String accessToken = wechatService.getAccessToken();
        String phoneNumber = wechatService.getPhoneNumber(accessToken, userLoginRequestDto.getPhoneCode(), openId);

        // 新用户：新增
        if(ObjectUtils.isNull(member)){
            // 3.id不存在，保存新用户
            // 随机组装昵称，词组+手机号后四位
            String nickName = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                    + StringUtils.substring(phoneNumber, 7);

            member.setOpenId(openId);
            member.setPhone(phoneNumber);
            member.setName(nickName);
            this.save(member);
        }else {   // 老用户：修改手机号(表中手机号和现在登录手机号不一致才会修改)
            if(!StrUtil.equals(member.getPhone(),phoneNumber)){
                member.setPhone(phoneNumber);
                this.updateById(member);
            }
        }
        // 三、产生token构建LoginVo对象
        Map<String, Object> claims = MapUtil.<String, Object>builder()
                .put("userId",member.getId())
                .put("nickName",member.getName())
                .build();
        String token = tokenService.createToken(claims);
        return LoginVo.builder().token(token).nickName(member.getName()).build();
    }

    @Override
    public MyVo getMy() {
     //   Long id = UserThreadLocal.getValue();
      //  FamilyMember member = this.getById(id);
        MyVo myVo = MyVo.builder()
                .id(1)
                .elderName("李天龙")
                .familyMemberId(2)
                .elderId(326)
                .build();
        return myVo;

    }

    @Override
    public void addBind(ElderDto elderDto) {

//        this.save()
    }
}
